<template>
  <view class="page-pwd">
    <view class="header">
      <view class="title">{{ $t('mine.提现') }}</view>
      <uni-icons type="left" color="#ffffff" size="24" class="back-icon" @click="handleBack"></uni-icons>
    </view>
    <uni-forms ref="form" :value="form" labelWidth="80px" class="form" label-position="top">
      <view class="methods">
        <view class="txt">{{ $t('mine.提现方式') }}</view>
        <view class="options">
          <radio-group @change="radioChange" style="transform: scale(0.9)">
            <label class="radio"><radio value="1" :checked="withdrawType == '1'" />银行卡</label>
            <label class="radio"><radio value="2" :checked="withdrawType == '2'" />USDT</label>
          </radio-group>
        </view>
      </view>
      <uni-forms-item name="money">
        <view class="money">
          <input class="input" type="txt" v-model="form.money" :placeholder="$t('mine.提现金额')" />
        </view>
      </uni-forms-item>
      <view class="desc">{{ $t('mine.可用余额') }}: {{ walletInfo.monneyBalance || 0 }} </view>
      <view class="account">{{ $t('mine.提款账号') }}</view>
      <uni-forms-item name="bankInfo">
        <view class="bank-info" @click="handleBackOpen">
          <view class="value">
            <input class="input" type="txt" v-model="form.bankInfo.bankCode" :placeholder="$t('mine.绑定提款账户')" disabled />
          </view>
          <view class="label">{{ $t('mine.收款信息') }}</view>
        </view>
      </uni-forms-item>
      <!-- <uni-forms-item name="cashPassword">
        <uni-easyinput type="password" v-model="form.cashPassword" :placeholder="$t('mine.输入交易密码')" />
      </uni-forms-item> -->
      <button type="primary" @click="submit" class="btn">{{ $t('mine.提现') }}</button>
    </uni-forms>
    <uni-popup ref="popup" type="bottom">
      <view class="popup-wrapper">
        <view class="popup-header">
          <uni-icons type="closeempty" size="20" @click="handleCancel"></uni-icons>
        </view>
        <view class="popup-content" v-if="bankListCpt.length > 0">
          <view class="list-card" v-for="(v, i) in bankListCpt" :key="i" @click="handleChooseBank(v)">
            <!-- <view class="bank-item">
              <view class="label">开户行</view>
              <view class="value">{{ v.bankNameSub }}</view>
            </view> -->
            <view class="bank-item column">
              <view class="label" v-if="v.bankType == 1">{{ $t('mine.银行卡') }}</view>
              <view class="label" v-else-if="v.bankType == 2">{{ $t('mine.USDT') }}</view>
              <view class="value">{{ v.bankCode | filterPrivacy }}</view>
            </view>
            <view class="bank-footer">
              <view class="label">{{ v.name }}</view>
              <view class="value">{{ v.bankName }}</view>
            </view>
          </view>
        </view>
        <view class="popup-content" v-else>
          <view class="empty">{{ $t('common.暂无数据') }}</view>
        </view>
      </view>
    </uni-popup>
    <!-- 输入密码 -->
    <CodePop type="1" v-if="showPay" @cancleCode="payCancle" @comfireCode="payComfire"></CodePop>
  </view>
</template>

<script>
  import CodePop from '@/components/CodePop/CodePop.vue'
  import { userbank } from '@/api/wallet.js'
  import { wallet, widthDrawConfig, withdraw } from '@/api/wallet.js'

  export default {
    components: {
      CodePop
    },
    data() {
      return {
        user: this.$store.state.user,
        withdrawType: '2',
        walletInfo: {},
        configId: '',
        bankList: [],
        form: {
          money: '',
          bankInfo: '',
          cashPassword: ''
        },
        rules: {
          money: {
            rules: [
              {
                required: true,
                errorMessage: this.$t('mine.提现金额不能为空')
              }
            ]
          },
          bankInfo: {
            rules: [
              {
                required: true,
                errorMessage: this.$t('mine.绑定提款账户不能为空')
              }
            ]
          },
          cashPassword: {
            rules: [
              {
                required: true,
                errorMessage: this.$t('mine.交易密码不能为空')
              }
            ]
          }
        },
        showPay: false
      }
    },
    computed: {
      bankListCpt() {
        return this.bankList.filter((v) => {
          return v.bankType == this.withdrawType
        })
      }
    },
    onPullDownRefresh() {
      this.getBankList()
      this.getWallet()
      this.getConfig()
      uni.stopPullDownRefresh()
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      // 支付取消
      payCancle() {
        this.showPay = false
      },
      // 支付完成
      payComfire(pwd) {
        this.showPay = false
        let postFrom = {
          money: this.form.money.trim(),
          bankinfo: this.form.bankInfo.id,
          cash_password: pwd,
          config_id: this.configId
        }
        this.$modal.loading('loading', 'loading')
        withdraw(postFrom)
          .then((response) => {
            this.$modal.closeLoading()
            this.$modal.msgSuccess(response.message)
            setTimeout(() => {
              this.handleBack()
            }, 500)
          })
          .catch((error) => {
            this.$modal.closeLoading()
          })
      },
      // 返回
      handleBack() {
        // this.$tab.navigateBack()
        this.$tab.navigateTo('/pages/mine/wallet/index')
      },
      //拉取数据
      getBankList() {
        this.$modal.loading('loading', 'loading')
        userbank()
          .then((res) => {
            this.$modal.closeLoading()
            let { bankList } = res.result
            this.bankList = bankList
          })
          .catch(() => {
            this.$modal.closeLoading()
          })
      },
      //选择银行卡
      handleBackOpen() {
        this.$refs.popup.open()
      },
      handleChooseBank(v) {
        this.form.bankInfo = v
        this.$refs.popup.close()
      },
      handleCancel() {
        this.$refs.popup.close()
      },
      //获取配置
      getConfig() {
        widthDrawConfig({ bank_type: this.withdrawType }).then((res) => {
          let { withdraw } = res.result
          this.configId = withdraw
        })
      },
      //获取钱包信息
      getWallet() {
        wallet().then((res) => {
          let { account } = res.result
          this.walletInfo = account || {}
        })
      },
      //提现方式改变
      radioChange(e) {
        this.withdrawType = e.detail.value
        this.form.bankInfo = {}
        this.getConfig()
      },
      //提交
      submit() {
        this.$refs.form.validate().then(() => {
          if (!this.user.password) {
            this.$modal.msgError(this.$t('mine.请先设置交易密码'))
            setTimeout(() => {
              this.$tab.navigateTo('/pages/mine/cashPwd/index')
            }, 1000)
            return
          }
          this.showPay = true
        })
      }
    },
    created() {
      this.getBankList()
      this.getWallet()
      this.getConfig()
    },
    filters: {
      filterPrivacy(val) {
        function maskString(str, options = {}) {
          if (!str) return ''
          const {
            preserveStart = 4, // 保留开头的字符数
            preserveEnd = 4, // 保留结尾的字符数
            maskChar = '*', // 掩码字符
            maskLength = null, // 自定义掩码长度（可选）
            blockSize = 4, // 分组大小
            separator = '' // 分组分隔符
          } = options
          // 清除所有分隔符（如果需要保留原始分隔符位置，可注释此行）
          const cleanStr = str.replace(/\s/g, '')
          const length = cleanStr.length
          // 处理长度不足的情况
          if (length <= preserveStart + preserveEnd) {
            return cleanStr
          }
          // 计算掩码部分长度
          const maskedLen = maskLength !== null ? Math.min(maskLength, length - preserveStart - preserveEnd) : length - preserveStart - preserveEnd
          // 生成掩码字符串
          const maskedPart = maskChar.repeat(maskedLen)
          // 截取前后保留部分
          const startPart = cleanStr.slice(0, preserveStart)
          const endPart = cleanStr.slice(-preserveEnd)
          // 组合结果
          let result = startPart + maskedPart + endPart
          // 格式化（每blockSize个字符添加一个分隔符）
          if (blockSize > 0 && separator) {
            result = result.match(new RegExp(`.{1,${blockSize}}`, 'g')).join(separator)
          }
          return result
        }
        return maskString(val)
      }
    }
  }
</script>

<style lang="scss" scoped>
  .page-pwd {
    position: relative;
    .header {
      background-color: #31b2b5;
      text-align: center;
      height: 44px;
      line-height: 44px;
      position: fixed;
      top: 0;
      width: 100vw;
      color: #fff;

      font-size: 26rpx;
      z-index: 9;
      .back-icon {
        position: absolute;
        left: 10px;
        top: 50%;
        transform: translateY(-50%);
        font-weight: normal;
      }
    }
    .form {
      margin: 120rpx 50rpx 0;
      .methods {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .txt {
          color: #00dede;
          padding-left: 21px;
          font-size: 16px;
          position: relative;
          &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #ffbd00;
          }
        }
        .options {
          .radio {
            margin-left: 40rpx;
            > uni-radio {
              margin-right: 10rpx;
            }
          }
        }
      }
      .money {
        margin-top: 40rpx;
        .input {
          height: 45px;
          line-height: 45px;
          // color: #999;
          background: #f3f3f3;
          padding: 0 16px;
          font-size: 14px;
        }
      }
      .desc {
        margin-top: 20rpx;
        display: flex;
        justify-content: flex-end;
      }
      .account {
        margin-top: 30px;
        margin-bottom: 20px;
        color: #00dede;
        padding-left: 21px;
        font-size: 16px;
        position: relative;
        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 12px;
          height: 12px;
          border-radius: 50%;
          background: #ffbd00;
        }
      }
      .bank-info {
        height: 45px;
        display: flex;
        align-items: center;
        background-color: #f3f3f3;
        border-radius: 4px;
        padding: 0 16px;
        .value {
          flex: 1;
          overflow: hidden;
          .input {
            font-size: 14px;
          }
        }
        .label {
          color: #0a85ff;
          white-space: nowrap;
          font-size: 26rpx;
        }
      }
      ::v-deep.uni-forms-item__label {
        height: 0;
      }
      ::v-deep.uni-easyinput__content {
        padding-left: 16px;
        background-color: #f3f3f3 !important;
        .uni-easyinput__content-input {
          height: 45px;
        }
      }
    }
    .btn {
      background: #31b3b5;
      width: 85vw;
      height: 40px;
      border-radius: 20px;
      font-size: 16px;
      color: #fff;
      line-height: 40px;
      text-align: center;
      margin: 100rpx auto 0;
    }
  }
  .popup-wrapper {
    background-color: #fff;
    border-radius: 16px 16px 0 0;
    height: 60vh;
    .popup-header {
      height: 45px;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding: 0 16px;
    }
    .popup-content {
      height: calc(100% - 45px);
      overflow-y: auto;
      padding: 0 16px;
      .list-card {
        background-color: #fff;
        border-radius: 6px;
        background: linear-gradient(135deg, #d7d7d7, #f3f3f3 48%, #b9b9b9);
        margin-bottom: 16px;
        padding: 16px;
        font-size: 26rpx;
        .bank-item {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
          &.column {
            flex-direction: column;
            align-items: flex-start;
            .value {
              margin-top: 10px;
              color: rgb(153, 153, 153);
              font-size: 28rpx;
            }
          }
        }
        .bank-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: 25px;
          color: #00a9a9;
        }
      }
      .empty {
        text-align: center;
      }
    }
  }
</style>
